import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

// types 设置类型
const types = {
  SET_LOCATION: 'SET_LOCATION',
  SET_ADDRESS: 'SET_ADDRESS'
}

// state 定义state（状态）
const state = {
  location: {},
  address: ''
}

// getters 定义getters
const getters = {
  // location: (state) => { return state.location}
  location: state => state.location,
  address: state => state.address
}

// mutations
const mutations = {
  // 本来第二个参数是payload（载荷）
  [types.SET_LOCATION](state,location) {
    // 第二参数传递如果存在，添加到state，否则为空
    if (location) {
      state.location = location
    } else {
      state.location = null
    }
  },
  [types.SET_ADDRESS] (state,address) {
    if (address) {
      state.address = address
    } else {
      state.address = ''
    }
  }
}

// actions 设置行为
const actions = {
  // https://vuex.vuejs.org/zh/guide/actions.html
  // https://www.cnblogs.com/xianrongbin/p/2781659.html
  /*
  context = {dispatch: local.dispatch,
    　　　　　　commit: local.commit,
    　　　　　　getters: local.getters,
    　　　　　　state: local.state,
    　　　　　　rootGetters: store.getters,
    　　　　　　rootState: store.state                         }*/
  // 使用 变量解构赋值后 { commit } 的 commit= context.commit 
  /*
  setLocation: (context, location) => {
    context.commit(types.SET_LOCATION,location)
  }
  */
  setLocation: ({commit}, location) => {
    commit(types.SET_LOCATION,location)
  },
  setAddress: ({commit}, address) => {
    commit(types.SET_ADDRESS,address)
  }
}

export default new Vuex.Store({
  state,
  getters,
  mutations,
  actions
})
